package work.wiwf.web.util;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.logging.LogFactory;
import com.gitee.fastmybatis.core.util.StringUtil;

public class DataSourceUtil {

	public static final String PREFIX = "base.datasource";
	
	/** 表新增时间字段名 */
	public static final String DbInsertDateColumnName = "create_time";
	/** 表更新时间字段名 */
	public static final String DbUpdateDateColumnName = "update_time";

	public static DataSource buildDataSource(String jdbcUrl, String driver, String username,
			String password) throws SQLException {
		DruidDataSource druid = new DruidDataSource();
		druid.setUrl(jdbcUrl);
		druid.setDriverClassName(driver);
		druid.setUsername(username);
		druid.setPassword(password);
		druid.setMaxActive(50);
		druid.setMaxWait(5 * 1000);
		druid.setInitialSize(3);

		// 时间：掉线检测间隔
		druid.setTimeBetweenEvictionRunsMillis(20 * 1000);
		// 时间:连接间隔错误
		druid.setTimeBetweenConnectErrorMillis(7 * 1000);

		// 失败后放弃
		// druid.setBreakAfterAcquireFailure(true);

		druid.setTestOnBorrow(true);
		druid.setTestWhileIdle(true);
		druid.setFailFast(false);

		if (jdbcUrl.lastIndexOf("mysql") > 0) {
			druid.setValidationQuery("select 1");
		}

		try {
			druid.init();
		} catch (Exception e) {
			LogFactory.getLog(DataSourceUtil.class).error(e.getMessage(), e);
		}
		return druid;
	}


	public static org.springframework.core.io.Resource getResource(String path) {
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		return resolver.getResource(path);
	}

	public static org.springframework.core.io.Resource[] getResources(String path) throws IOException {
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		
		List<org.springframework.core.io.Resource> arrayList = new ArrayList<org.springframework.core.io.Resource>();
		String[] paths = StringUtil.tokenizeToStringArray(path,
				StringUtil.CONFIG_LOCATION_DELIMITERS);
		for (String p : paths) {
			org.springframework.core.io.Resource[] resources = resolver.getResources(p);
			for (org.springframework.core.io.Resource resource : resources) {
				arrayList.add(resource);
			}
		}
		
		org.springframework.core.io.Resource[] resources = new org.springframework.core.io.Resource[arrayList.size()];
		for (int i = 0; i < arrayList.size(); i++) {
			resources[i] = arrayList.get(i);
		}
		
		return resources;
	}
}
